$(function () {
    //  微型消防站管理 打开窗口
    $('.miniFireStation-trigger').on('click', function (event) {
        event.preventDefault();
        $('.miniFireStation-pop').addClass('is-visible3');
        // 微型消防站管理 首次渲染
        var miniFireStationPage = 1;
        miniFireStationPageList(miniFireStationPage);
        // 微型消防站管理 获取总页数 点击分页渲染列表
        miniFireStationSumPage(miniFireStationPage);
        $('.pageJump input').val('');
    });
    //微型消防站管理  关闭窗口
    $('.miniFireStation-pop').on('click', function (event) {
        if ($(event.target).is('.cd-popup-close') || $(event.target).is('.miniFireStation-pop')) {
            event.preventDefault();
            $(this).removeClass('is-visible3');
        }
    });
    //    ------------------添加-------------------
    //  微型消防站添加 打开窗口
    $('.addFireStation-trigger').on('click', function (event) {
        event.preventDefault();
        $('.addFireStation-pop').addClass('is-visible3');
        $("#addFireStationForm .fireStationVal").val('fireStation');
        getOrgFunc();

    });
    //微型消防站添加  关闭窗口
    $('.addFireStation-pop').on('click', function (event) {
        if ($(event.target).is('.cd-popup-close') || $(event.target).is('.addFireStation-pop')) {
            event.preventDefault();
            $(this).removeClass('is-visible3');
            //Modal验证销毁重构
            $("#addFireStationForm").data('bootstrapValidator').destroy();
            $('#addFireStationForm').data('bootstrapValidator', null);
            addFireStationFormValidator();
            $('#addFireStationForm input').val('');
        }
    });

    // 微型消防站添加页面 点击上传相片
    var picThat;
    var multipartFile;
    var file;
    var imgUpload = 0;
    $("#addFireStationModal .addFireStationLogo").on("click", '.pic', function () {
        console.log(this);
        $(this).parent().find(".upload").click(); //隐藏了input:file样式后，点击头像就可以本地上传
        $(this).parent().find(".upload").on("change", function (e) {
            imgUpload++;
            console.log(this.files[0]);
            var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
            console.log(objUrl);
            picThat = this;
            console.log(this);
            if (objUrl) {
                $(this).parent().removeClass("bac");
                $(this).parent().find(".pic").css("opacity", 1);
                $(this).parent().find(".pic").attr("src", objUrl); 
                $(this).parent().find(".pic").addClass('opacity1');
            } else {
                $(this).parent().find(".pic").removeClass('opacity1');
            }   
        });
    });

    function getObjectURL(file) {
        var url = null;
        if (window.createObjectURL != undefined) { // basic
        url = window.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }

    // 微型消防站 添加页面的 删除头像
    $("#addFireStationModal .del").on("click", function(){
        $(this).siblings('.pic').attr('src', '');
        multipartFile = {};    
        $(this).siblings('.pic').removeClass('opacity1');
        $("#addFireStationModal .pic").css("opacity", 0);
        $("#addFireStationModal").find(".addFireStationLogo").addClass("bac");
    });

    // 微型消防站 修改页面 点击上传图片
    var picThatEdit;
    var multipartFileEdit;
    $("#editFireStationForm .editFireStationLogo").on("click", '.pic', function () {
        console.log(this);
        $(this).parent().find(".upload").click(); //隐藏了input:file样式后，点击头像就可以本地上传
        $(this).parent().find(".upload").on("change", function (e) {
            console.log(this.files[0]);
            var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
            console.log(objUrl);
            picThat = this;
            console.log(this);
            if (objUrl) {
                $(this).parent().removeClass("bac");
                $(this).parent().find(".pic").css("opacity", 1);
                $(this).parent().find(".pic").attr("src", objUrl); 
                $(this).parent().find(".pic").addClass('opacity1');
            } else {
                $(this).parent().find(".pic").removeClass('opacity1');
                $(this).parent().addClass("bac");
            }   
        });
    });

    // 微型消防站添加  获取所有组织
    function getOrgFunc() {
        $.ajax({
            url: '/organization/list?type=street',
            success: function (res) {
                console.log(res)
                $('#addFireStationModal .choiceStreet').html('');
                for (var i = 0; i < res.data.length; i++) {
                    $('#addFireStationModal .choiceStreet').append('<option value="' + res.data[i].id + '" selected>' + res.data[i].orgName + '</option>');
                }
            }
        });
    }
    //微型消防站管理 获取总页数 点击分页渲染列表
    function miniFireStationSumPage(miniFireStationPage) {
        var pageSum;
        $.ajax({
            // url:'/paging/organization/pageNumber?type=fireStation',
            url: '/paging/organizationfire/pageNumber?type=fireStation',
            async: false,
            success: function (result) {
                console.log(result);
                pageSum = result.data;
                console.log(pageSum, miniFireStationPage)
                miniFireStationPageFunc(pageSum, miniFireStationPage)
            }
        });
    }
    //微型消防站管理  分页功能
    function miniFireStationPageFunc(pageSum, miniFireStationPage) {
        if (pageSum <= 1) {
            $('#miniFireStationPageBox .pageJump').hide()
        } else {
            $('#miniFireStationPageBox .pageJump').show()
        }
        Page({
            num: pageSum, //页码数
            startnum: miniFireStationPage, //指定页码
            elem: $('#miniFireStationPage'), //指定的元素
            callback: function (n) { //回调函数
                console.log(n);
                miniFireStationPageList(n);
            }
        });
    };
    //微型消防站管理  页面渲染列表
    function miniFireStationPageList(n) {
        var roleid;
        var displayStr;
        $.ajax({
            url: "/user/get",
            type: "GET",
            async: false,
            success: function (result) {
                console.log(result)
                if (result.status == "200") {
                    roleid = result.data.role.roleId;
                    console.log(roleid)
                } else {

                }
            }
        });

        $.ajax({
            url: '/role/get/' + roleid,
            async: false,
            success: function (res) {
                console.log(res)
                if (res.data.modifiable == 1) {
                    displayStr = "table-cell";
                } else {
                    displayStr = "none";
                }
            }
        });
        $.ajax({
            // url:'/paging/organization/approve?type=fireStation&page='+n,  
            url: '/paging/organizationfire/approve?type=fireStation&page=' + n,
            async: false,
            success: function (result) {
                console.log(result)
                $('#miniFireStationModal .tbodyList').html('');
                miniFireStationPage = n;
                var data = result.data;
                if (data.length != 0) {
                    for (var i = 0; i < data.length; i++) {
                        console.log(data[i][0].orgid)
                        var hangUp = data[i][1];
                        $('#miniFireStationModal .tbodyList').append('<tr><td><input type="checkbox" class="check" thisid="' + data[i][0].id + '"></th><th>' + ((+n - 1) * (+8) + (+i) + (+1)) + '</th><th>' + data[i][0].orgName + '</td><td>' + data[i][0].parent.orgName + '</td><td>' + hangUp + '</td><td class=" ' + displayStr + '"><span class="configBtnStyle modifyBtn margin0 editFireStation-trigger" orgName="' + data[i][0].orgName + '" orgid="' + data[i][0].orgid + '" parentOrgName="' + data[i][0].parent.orgName + '" centrex="' + data[i][0].centrex + '" centrey="' + data[i][0].centrey + '" parentid="' + data[i][0].parent.id + '" telephone="' + data[i][0].telephone + '" personal="' + data[i][0].personal + '" photoUrl="' + data[i][0].photoUrl + '">修改</span></td></tr>');
                    }
                } else {
                    if (miniFireStationPage > 1) {
                        miniFireStationPage = miniFireStationPage - 1;
                    } else {
                        return false;
                    }
                    // 微型消防站管理 首次渲染
                    miniFireStationPageList(miniFireStationPage);
                    // 微型消防站管理 获取总页数 点击分页渲染列表
                    miniFireStationSumPage(miniFireStationPage);
                    $('.pageJump input').val('');
                }
            }
        });
    };
    //    ---------------------添加-------------------
    // 微型消防站添加  验证form表单
    addFireStationFormValidator();
    function addFireStationFormValidator() {
        $("#addFireStationForm").bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                orgName: {
                    validators: {
                        notEmpty: {
                            message: '名称不能为空'
                        },
                        remote: {
                            url: '/organization/org/validateName',
                            data: {
                                'orgName': $('#addFireStationForm .orgNameVal').val(),
                            },
                            type: 'POST',
                            delay: 1000,
                            message: "名称已存在",
                        },
                    }
                },
                parentid: {
                    validators: {
                        notEmpty: {
                            message: '所属街道不能为空'
                        }
                    }
                },
                Personal: {
                    validators: {
                        notEmpty: {
                            message: '联系人不能为空'
                        }
                    }
                },
                telephone: {
                    validators: {
                        notEmpty: {
                            message: '联系电话不能为空'
                        }
                    }
                },
                centrex: {
                    validators: {
                        notEmpty: {
                            message: '经度不能为空'
                        }
                    }
                },
                centrey: {
                    validators: {
                        notEmpty: {
                            message: '纬度不能为空'
                        }
                    }
                }
            }
        }).on("success.form.bv", function (e) {
            var time = Date.now();
            e.preventDefault();
            // 图片上传
            console.log(multipartFile);
            var $form = $(e.target);
            var obj = new FormData($form[0]);
            var nextUrl;
            // nextUrl = "/device/save?orgid=1"+'&'+$form.serialize(); 
            nextUrl = "/organization/save?orgid=" + time, //localhost:9092/user/save?orgid=1&roleId=1
            console.log($form.serialize());
            console.log(obj)
            $.ajax({
                url: nextUrl,
                type: 'POST',
                async: false,
                data: obj,
                contentType: false,
                processData: false,
                success: function (result) {
                    console.log(result)
                    if (result.status == 200) {
                        $('.addFireStation-pop').removeClass('is-visible3');                        
                        tipModalFunc('添加成功!');
                        // 清除照片
                        obj = {};
                        $('#addFireStationForm .pic').attr('src', '');
                        $("#addFireStationForm .pic").css("opacity", 0);
                        $('#addFireStationForm .pic').removeClass('opacity1');
                        $("#addFireStationForm").find(".addFireStationLogo").addClass("bac");
                        //Modal验证销毁重构
                        $("#addFireStationForm").data('bootstrapValidator').destroy();
                        $('#addFireStationForm').data('bootstrapValidator', null);
                        addFireStationFormValidator();
                        $('#addFireStationForm input').val('');
                        $("#addFireStationForm select").val('全部');
                        fireStationNum();
                    } else {
                        console.log(result.message);
                        addFireStationFormValidator();
                    }
                }
            });
            // 微型消防站管理 首次渲染
            // var miniFireStationPage = 1;
            console.log(miniFireStationPage)
            miniFireStationPageList(miniFireStationPage);
            // 微型消防站管理 获取总页数 点击分页渲染列表
            miniFireStationSumPage(miniFireStationPage);
            $('.pageJump input').val('');
        });
    }
    //  ------------------修改-------------------
    //  微型消防站修改 打开窗口
    $('body').on('click', '.editFireStation-trigger', function (event) {
        var $this = $(this);
        event.preventDefault();
        $('.editFireStation-pop').addClass('is-visible3');
        $("#editFireStationForm .fireStationVal").val('fireStation');
        // getOrgFunc();
        // 获取图片
        var photoUrl = $this.attr('photoUrl');
        console.log(photoUrl);
        if (photoUrl != 'null') {
            $("#editFireStationForm .editFireStationLogo").find(".pic").attr("src", photoUrl);
            $("#editFireStationForm .editFireStationLogo").find(".pic").addClass('opacity1');
            $("#editFireStationForm .editFireStationLogo").find(".pic").css("opacity", 1);
        } else {
            $("#editFireStationForm .editFireStationLogo").find(".pic").removeClass('opacity1');
            $("#editFireStationForm .editFireStationLogo").find(".pic").css("opacity", 0);
            $("#editFireStationForm .editFireStationLogo").addClass("bac");
        }
        

        var orgName = $this.attr('orgName');
        var parentOrgName = $this.attr('parentOrgName');
        var centrex = $this.attr('centrex');
        var centrey = $this.attr('centrey');
        var parentid = $this.attr('parentid');
        var telephone = $this.attr('telephone');
        var personal = $this.attr('personal');
        var orgid = $this.attr('orgid');
        var id = $this.parent().parent().find('input').attr('thisid');
        //        console.log($this.parent().find('input'))
        $('#editFireStationForm .orgNameVal').val(orgName);
        //        $('#editFireStationForm .choiceStreet').find("option:contains('"+parentOrgName+"')").attr("selected",true);
        $('#addFireStationModal .choiceStreet').html('<option value="' + parentid + '" selected>' + parentOrgName + '</option>');
        $('#editFireStationForm .PersonalVal').val(personal);
        $('#editFireStationForm .telephoneVal').val(telephone);
        $('#editFireStationForm .centrex').val(centrex);
        $('#editFireStationForm .centrey').val(centrey);
        $('#editFireStationForm .orgidVal').val(orgid);
        $('#editFireStationForm .idVal').val(id);
    });


    //微型消防站修改  关闭窗口
    $('.editFireStation-pop').on('click', function (event) {
        if ($(event.target).is('.cd-popup-close') || $(event.target).is('.editFireStation-pop')) {
            event.preventDefault();
            $(this).removeClass('is-visible3');
        }
    });

    // 微型消防站修改  验证form表单
    editFireStationFormValidator();
    function editFireStationFormValidator() {
        $("#editFireStationForm").bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                orgName: {
                    validators: {
                        notEmpty: {
                            message: '名称不能为空'
                        },
                    }
                },
                parentid: {
                    validators: {
                        notEmpty: {
                            message: '所属街道不能为空'
                        }
                    }
                },
                Personal: {
                    validators: {
                        notEmpty: {
                            message: '联系人不能为空'
                        }
                    }
                },
                telephone: {
                    validators: {
                        notEmpty: {
                            message: '联系电话不能为空'
                        }
                    }
                },
                centrex: {
                    validators: {
                        notEmpty: {
                            message: '经度不能为空'
                        }
                    }
                },
                centrey: {
                    validators: {
                        notEmpty: {
                            message: '纬度不能为空'
                        }
                    }
                }
            }
        }).on("success.form.bv", function (e) {
            e.preventDefault();
            var $form = $(e.target);
            var obj = new FormData($form[0]);
            var nextUrl;
            // nextUrl = "/device/save?orgid=1"+'&'+$form.serialize(); 
            var parentid = $('#editFireStationForm .choiceStreet').val();
            nextUrl = "/organization/save?parentid="+parentid, //根据orgID修改
            console.log($form.serialize())
            $.ajax({
                url: nextUrl,
                type: 'POST',
                async: false,
                data: obj,
                contentType: false,
                processData: false,
                success: function (result) {
                    console.log(result)
                    if (result.status == 200) {
                        $('.editFireStation-pop').removeClass('is-visible3');
                        tipModalFunc('修改成功!');
                        // 清除照片
                        obj = {};
                        $('#editFireStationForm .pic').attr('src', '');
                        $("#editFireStationForm .pic").css("opacity", 0);
                        $('#editFireStationForm .pic').removeClass('opacity1');
                        $("#editFireStationForm").find(".editFireStationLogo").addClass("bac");
                        //Modal验证销毁重构
                        $("#editFireStationForm").data('bootstrapValidator').destroy();
                        $('#editFireStationForm').data('bootstrapValidator', null);
                        editFireStationFormValidator();
                        $('#editFireStationForm input').val('');
                        $("#editFireStationForm select").val('全部');
                    } else {
                        console.log(result.message);
                    }
                }

            });

            miniFireStationPageList(miniFireStationPage);
            // 微型消防站管理 获取总页数 点击分页渲染列表
            miniFireStationSumPage(miniFireStationPage);
            $('.pageJump input').val('');
        });
    }


    //全选删除/全不选
    $('#miniFireStationSelectAll').click(function () {
        var current = $(this).prop('checked');
        $('.check').prop({
            checked: current
        });
    });

    $('#miniFireStationModal').on('click', '.check', function () {
        var flag = true;
        //  遍历下面所有的状态
        for (var i = 0; i < $('.check').length; i++) {
            //            如果其中一个不满足条件，把状态设置成false，立刻跳出循环
            if ($('.check').eq(i).prop('checked') == false) {
                flag = false;
                break;
            }
        }
        $('#miniFireStationSelectAll').prop({
            checked: flag
        });
    });

    //  删除微型消防站
    $("#miniFireStationDelBtn").on('click', function () {
        $('#miniFireStationModal .table .tbodyList input[type=checkbox]:checked').each(function () {
            var thisid = $(this).attr('thisid');
            $.ajax({
                url: '/organization/delete/' + thisid,
                type: 'POST',
                async: false,
                success: function (res) {
                    console.log(res)
                    fireStationNum();
                }
            });
        });

        miniFireStationPageList(miniFireStationPage);
        // 微型消防站管理 获取总页数 点击分页渲染列表
        miniFireStationSumPage(miniFireStationPage);
        $('#miniFireStationSelectAll').prop('checked', false)
        tipModalFunc('删除成功!');
    });


});

  // 地图上的查看详情点击查看详情
  function fireStationSeeDetailsFunc1(){
    $("body .fireStationSeeDetails").on("click", function (event) {
      event.preventDefault();
      var $this = $(this);
      console.log(this);
      $('.detailFireStation-pop').addClass('is-visible3');
      $('#detailFireStationForm .rowAdd').eq(0).find('input').val($this.attr('orgName'));
      $('#detailFireStationForm .rowAdd').eq(2).find('input').val($this.attr('personal'));
      $('#detailFireStationForm .rowAdd').eq(3).find('input').val($this.attr('telephone'));
      $('#detailFireStationForm .rowAdd').eq(4).find('input').val($this.attr('latitude'));
      $('#detailFireStationForm .rowAdd').eq(5).find('input').val($this.attr('longitude'));
      $('#detailFireStationModal .detailFireStationLogo').html('<img src="'+$this.attr('photoUrl')+'" alt="">');
      $.ajax({
        url: '/organization/list?type=street',
        success: function (res) {
            console.log(res)
            $('#detailFireStationForm .detailFireStationFormOrgList').html('');
            for (var i = 0; i < res.data.length; i++) {
                $('#detailFireStationForm .detailFireStationFormOrgList').append('<option value="' + res.data[i].id + '" selected>' + res.data[i].orgName + '</option>');
            }
            $('#detailFireStationForm .detailFireStationFormOrgList').val($this.attr('parentid'));
        }
    });
    });
  
  }